from pydantic import BaseModel, Field


class InterfaceInfoSchema(BaseModel):
    interface_name: str = Field(..., description="接口名称")
    import_package_path: str = Field(None, description="接口导包路径")
    interface_define_content: str = Field(None, description="接口定义内容")
    interface_implement_example: str = Field(None, description="接口实现示例")


# 定义mcp工具函数
def interface_tool(
        interface_name_list: list[str] = Field(..., description="接口名称列表")
) -> list[InterfaceInfoSchema]:
    items = []
    for interface_name in interface_name_list:
        item = fetch_interface_info(interface_name)
        items.append(item)
    return items


def fetch_interface_info(interface_name: str) -> InterfaceInfoSchema:
    resp = InterfaceInfoSchema(interface_name=interface_name)
    if interface_name == 'ConfigType':
        resp.interface_define_content, resp.interface_implement_example, resp.import_package_path = ConfigTypeInterface()
    elif interface_name == 'FrontCodeInstance':
        resp.interface_define_content, resp.interface_implement_example, resp.import_package_path = FrontCodeInstanceInterface()
    elif interface_name == 'ExcelParser':
        resp.interface_define_content, resp.interface_implement_example, resp.import_package_path = ExcelParserInterface()
    elif interface_name == 'ITemplateInstance':
        resp.interface_define_content, resp.interface_implement_example, resp.import_package_path = ITemplateInstanceInterface()
    else:
        raise Exception('接口名称不存在')
    return resp


def ITemplateInstanceInterface() -> (str, str, str):
    content = """// ITemplateInstance 模板实例 v3实现的
type ITemplateInstance interface {
	// TemplateType tqt定义的唯一key
	TemplateType() EnumTemplateType
	// Version 模板版本
	Version() Version
	// MatchExcelParser Excel解析匹配 by name & version
	MatchExcelParser(ctx context.Context, name string, version Version) (ExcelParser, error)
	// GetExcelParser 模板的Excel解析器
	GetExcelParser() ExcelParser
	// ValidateTemplateData 校验模板数据
	ValidateTemplateData(ctx context.Context, entity ITemplateEntity) ([]Warning, error)
	// GetConfig 获取活动配置
	GetConfig() ConfigType
	// ToSvrConfig 转换成服务端数据结构
	ToSvrConfig(ctx context.Context, entity ITemplateEntity, extraParams map[string]interface{}) (map[string]interface{}, error)
	// ToTqtConfig 服务端数据转tqt格式
	ToTqtConfig(ctx context.Context, config map[string]interface{}) (map[string]interface{}, error)
}"""

    implement_example = """import (
	"context"
	"fmt"
	"tongquetai_server/activity_vk/domain/manage"
	"tongquetai_server/activity_vk/domain/manage/common/validator"
	"tongquetai_server/activity_vk/domain/manage/common/copier_option"
	"tongquetai_server/activity_vk/domain/manage/common/static_data"
	"tongquetai_server/activity_vk/domain/manage/common/value"
	"tongquetai_server/share/infrastructure/utils"
)

func (t *TqtConfig) ValidateTemplateData(ctx context.Context, entity manage.ITemplateEntity) ([]manage.Warning,error) {
	tqtConfig := entity.GetConfig().(*TqtConfig)
	// 活动天数奖励配置
	err := validateDailyAwards(ctx, tqtConfig.DailyAwards)
	if err != nil {
		return nil, err
	}
	return nil, nil
}

// ToTqtConfig 服务端数据转tqt格式
func (t *TqtConfig) ToTqtConfig(ctx context.Context, config map[string]interface{}) (res map[string]interface{}, err error) {
	svrConfig := SvrConfig{}
	err = utils.MapToStruct(config, &svrConfig)
	if err != nil {
		return
	}
	tqtConfig := &TqtConfig{}
	// 使用copier自动转
	err = copier.CopyWithOption(tqtConfig, svrConfig, copier_option.NewCopierOption(
		copier_option.NewSvrToTqtItemOption(ctx),
		copier_option.NewSvrToTqtAwardOption(ctx),
		copier_option.NewSvrToTqtAwardWithWeightOption(ctx),
	))
	if err != nil {
		return
	}
	// 将铜雀台结构体转map格式
	res = utils.StructToMap(tqtConfig)
	return
}

// ToSvrConfig 转换成服务端数据结构
func (t *TqtConfig) ToSvrConfig(ctx context.Context, entity manage.ITemplateEntity,
	extraParams map[string]interface{}) (res map[string]interface{}, err error) {
	svrConfig := SvrConfig{}
	tqtConf := entity.GetConfig().(*TqtConfig)
	// 使用copier自动转
	err = copier.CopyWithOption(&svrConfig, entity.GetConfig(), copier_option.NewCopierOption(
		copier_option.NewTqtToSvrItemOption(),
		copier_option.NewTqtToSvrAwardOption(),
		copier_option.NewTqtToSvrAwardWithWeightOption(),
	))
	if err != nil {
		return
	}
	// 将服务端结构体转map格式
	res = utils.StructToMap(svrConfig)
	return
}
"""
    import_package_path = "tongquetai_server/activity_vk/domain/manage"
    return content, implement_example, import_package_path


def ExcelParserInterface() -> (str, str, str):
    content = """// ExcelParser v3 Excel解析接口定义
type ExcelParser interface {
	// Parse 解析Excel方法
	Parse(context.Context, sheet.Sheet) (ITemplateEntity, error)
	// Export 导出为Excel方法
	Export(ctx context.Context, entity ITemplateEntity) (sheet.Sheet, error)
}"""
    implement_example = """import (
	"context"
	"tongquetai_server/activity_vk/domain/manage"
	"tongquetai_server/activity_vk/domain/manage/common/block"
	"tongquetai_server/activity_vk/domain/manage/common/exporter"
	"tongquetai_server/activity_vk/domain/manage/common/front"
	"tongquetai_server/activity_vk/domain/manage/common/parser"
	"tongquetai_server/activity_vk/infrastructure/excel_reader"
	"tongquetai_server/activity_vk/infrastructure/utils"
	utils2 "tongquetai_server/share/infrastructure/utils"
	"tongquetai_server/share/infrastructure/utils/excel_template/excel/sheet"
)
type excelParser struct {
	fileName string
}

func (e *excelParser) getBlocks(sheetName string) []excel_reader.Block {
	return []excel_reader.Block{
		// 支持排期：跨合区联盟排期
		block.GetNoServerBaseInfoBlock("baseInfo", e.fileName, sheetName),
	}
}

func (e *excelParser) Parse(ctx context.Context, st sheet.Sheet) (entity manage.ITemplateEntity, err error) {
	ctx = context.WithValue(ctx, "actType", ActType)
	tagBlocks, err := excel_reader.AutoGenerateParserBlockByTag(ctx, &TqtConfig{})
	if err != nil {
		return nil, err
	}
	blocks := append(e.getBlocks(st.Name), tagBlocks...)
	var resultStruct = struct {
		BaseInfo parser.BaseInfo `json:"baseInfo"`
		TqtConfig
	}{}
	// 解析
	r := excel_reader.NewExcelReader(ctx, st, blocks...)
	err = r.GetAllDataStruct(&resultStruct)
	if err != nil {
		return
	}

	entity, err = utils.NewTemplateByParams(
		ActivityTemplateType,
		resultStruct.BaseInfo.BigType,
		resultStruct.BaseInfo.ActType,
		resultStruct.BaseInfo.TemplateName,
		resultStruct.BaseInfo.ZoneSize,
		string(ActivityVersion),
		resultStruct.BaseInfo.StartTime,
		resultStruct.BaseInfo.EndTime,
		&resultStruct.TqtConfig,
	)

	return
}

func (e *excelParser) Export(ctx context.Context, entity manage.ITemplateEntity) (st sheet.Sheet, err error) {
	baseInfo, err := exporter.EntityToBaseInfo(ctx, entity)
	if err != nil {
		return
	}
	data := utils2.StructToMap(entity.GetConfig())
	data["baseInfo"] = utils2.StructToMap(baseInfo)

	tagBlocks, err := excel_reader.AutoGenerateExporterBlockByTag(ctx, &TqtConfig{})
	if err != nil {
		return st, err
	}
	blocks := append(e.getBlocks(st.Name), tagBlocks...)
	table, err := excel_reader.ExportToTableByBlocks(ctx, data, blocks)
	if err != nil {
		return
	}

	return table.ToSheet(entity.GetTemplateName()), nil
}"""
    import_package_path = "tongquetai_server/activity_vk/domain/manage"
    return content, implement_example, import_package_path


def FrontCodeInstanceInterface() -> (str, str, str):
    content = """// FrontCodeInstance 前端配置
type FrontCodeInstance interface {
	FrontCode(ctx context.Context) (fc excel_reader.FrontCode, err error)
}"""
    implement_example = """type TqtConfig struct {}

func (t *TqtConfig) FrontCode(ctx context.Context) (fc excel_reader.FrontCode, err error) {
	tagBlock, err := excel_reader.AutoGenerateFrontBlockByOtherTag(ctx, &TqtConfig{}, "content", true)
	if err != nil {
		return nil, err
	}
	blocks := append(front.GetBaseInfoFrontendBlock(), tagBlock...)
	fc, err = excel_reader.FrontToCodeByBlocks(ctx, blocks)
	if err != nil {
		return nil, err
	}
	return fc, err
}"""
    import_package_path = "tongquetai_server/activity_vk/domain/manage"
    return content, implement_example, import_package_path


def ConfigTypeInterface() -> (str, str, str):
    content = """// ConfigType v3模板配置 interface
type ConfigType interface {
	ToJson() (string, error)                  // 转json
	ToEntity(data string) (ConfigType, error) // 转实体
}"""
    implement_example = """import (
	"tongquetai_server/activity_vk/domain/manage"
	"tongquetai_server/activity_vk/infrastructure/errors"
	"tongquetai_server/share/infrastructure/utils"
	"tongquetai_server/share/infrastructure/utils/json"
)

type TqtConfig struct{}

func (t *TqtConfig) ToJson() (string, error) {
	return json.JsonMarshalString(t)
}

func (t *TqtConfig) ToEntity(data string) (manage.ConfigType, error) {
	res := &TqtConfig{}
	err := utils.JsonUnmarshal(data, res)
	if err != nil {
		return nil, errors.ErrTemplateConfig(err)
	}
	return res, nil
}
    """
    import_package_path = "tongquetai_server/activity_vk/domain/manage"
    return content, implement_example, import_package_path
